/**
 * Mydesk site extensions
 * ************************************************************************************************************
 */

site.extension('Tabs', {
	
	TabControl: function() {
		
		var tabs = {},
		activeTabId = null;
		
		this.addTab = function(tabId, btnElement, viewElements) {
			
			if(tabs[tabId])
				return;
			
			tabs[tabId] = {
				button: btnElement,
				elements: viewElements
			};
		};
		
		this.changeTab = function(tabId) {
			
			if(tabId === activeTabId)
				return;
			
			if(activeTabId) {
				var tab = tabs[activeTabId];	
				tab.button.removeClass('active');
				
				activeTabId = tabId;
				var newTab = tabs[activeTabId];	
				newTab.button.addClass('active');
				
				tab.elements.hide();
				newTab.elements.show();
				
			} else {
				
				for(var tab in tabs) {
					if(tabs.hasOwnProperty(tab)) {
						tabs[tab].elements.hide();
						tabs[tab].button.removeClass('active');
					}
				}
				
				activeTabId = tabId;
				var tab = tabs[activeTabId];	
				tab.button.addClass('active');
				tab.elements.show();
			}
		};	
		
		this.getActiveTabId = function() {
			return activeTabId;
		}
	}
});

site.extension('TextboxList', {
	create : function(el, options) {
		return new $.TextboxList(el, options);
	}
});

site.extension('FileUploader', {
	create : function(options) {
		return new qq.FileUploader(options);
	}
});

site.extension('jCrop', {
	create : function(el, options, callback) {
		return $(el).Jcrop(options, callback);
	}
});

/**
 * Project extensions
 * ************************************************************************************************************
 */

site.extension('fixedProjectHeader', {
	init : function() {
		
		var top = 0
    
	    if ($(window).scrollTop() > 35){
	            
	                $('#project_header').css({'top':'25px'});
	                                      
	             }
	             else {
	                 top = 60 - $(window).scrollTop();
	                 $('#project_header').css({'top': top + 'px'});
	             }
	   
	     $(window).scroll(function () {
	      
	         if ($(this).scrollTop() > 35){
	            
	                $('#project_header').css({'top':'26px',
	                                          'box-shadow':'0px 5px 8px -4px #000',
	                                          '-moz-box-shadow':'0px 5px 8px -4px #000',
	                                          '-webkit-box-shadow':'0px 5px 8px -4px #000'});
	                                      
	             }
	             else {
	                 top = 60 - $(this).scrollTop();
	                 $('#project_header').css({'top': top + 'px',
	                                           'box-shadow':'none',
	                                           '-moz-box-shadow':'none',
	                                           '-webkit-box-shadow':'none'});
	             }
	             
	    });
	}
});

/**
 * Action dialog extensions
 * ************************************************************************************************************
 */

site.extension('actionDialog', {
	create: function (element, onsuccess) {
       
        if(typeof(element) === 'undefined')
            return false;
				
		$('body').delegate(element, 'click', function(event){

			var content = $(this).attr('rel').split('|');
			$('body').append('<section id="msg-prompt"  class="overlay msg-prompt">' + 
	                                    '<header>'+ content[0] +'</header>' + 
	                                    '<div id="msg-content">' + content[1] + '</div>' + 
	                                    '<div id="msg-action"><a id="overlay_accept" class="button_blue">' + content[2] +'</a> <a id="overlay_cancel" class="button_grey">'+ content[3] +'</a></div>' +
	                                 '</section>');
			var that = $(this);
	                
			var overlay_message = $('#msg-prompt').overlay(
			{
				top: 210,
				mask: {color: '#000', loadSpeed: 400, opacity: 0.5},
				closeOnClick: false,
				load: true,
				onClose: function() {$('#msg-prompt').remove();}	
			});
			
			$('#overlay_accept').click( function(){
			
					overlay_message.overlay().close();
					onsuccess(that);
								
			});
			
			$('#overlay_cancel').click( function(){
					overlay_message.overlay().close();
			});	

	               
			event.preventDefault();
			//return false;
		});
	}

});

/**
 * Tipsy extensions
 * ************************************************************************************************************
 */

site.extension('tipsy', {
	init: function(el, settings) {
		$(el).tipsy(util.extend({
			gravity: 'se',
			trigger: 'hover'
		}, settings));
	}
});

/**
 * Slim scroll extensions
 * ************************************************************************************************************
 */

site.extension('slimScroll', {
	init: function(el, options) {
		$(el).slimScroll(options);
	}
});

 /**
 * toggle info boxes extensions
 * ************************************************************************************************************
 */

 site.extension('toggleBox', {
	init: function(settings) {
	    var o = util.extend({
				anchor: '',
				box: '',
				onToggle: function(){},
				beforeToggle: function(){}
			}, settings),

	    	element_anchor = $(o.anchor),
			element_box = $(o.box);
		//don't hide box when you click on it 
		element_box.on('click', function(e) {
			e.stopPropagation();
		});

		//bind event on click on anchor to show or hide box
		element_anchor.on('click', function(e) {
			o.beforeToggle.call(element_anchor)

			element_box.toggle();
			element_anchor.toggleClass('active');
			o.onToggle.call(element_anchor);

			e.preventDefault();
			e.stopPropagation();
		})
	}
});

/**
 * Iphone swicht extensions
 * ************************************************************************************************************
 */

site.extension('switch', {
	init: function(el, settings) {
		var element = $(el),
			message = element.attr('data-content').split('|');
		
		settings = util.extend({
			onChange: function(toggle) {}
		}, settings);

		element.on('change', function() {
			var self = $(this);
			settings.onChange.call(self, self.is(':checked'));
		});
		
		element.iphoneStyle({checkedLabel: message[0], //$(this).attr('data-switch-on') , 
                         uncheckedLabel: message[1], //$(this).attr('data-switch-off'), 
                         resizeContainer: false, 
                         resizeHandle: false});
	}
});


/**
 * Color picker extensions
 * ************************************************************************************************************
 */

 site.extension('colorPicker', {
 	init: function(el, settings) {
 		var element = $(el),
			
			settings = util.extend({
				onSubmit:  function(hsb, hex, rgb, el) {},
				onBeforeShow: function () {}
			}, settings);

		$('.colorpicker').remove();

		element.ColorPicker({
            eventName: 'focus',

            onSubmit:  function(hsb, hex, rgb, el) {
                settings.onSubmit.apply(element, arguments);
            },
            onBeforeShow: function () {
            	settings.onBeforeShow.apply(element, arguments);
            }
        }); 
 	}
 });

 /**
 *	Submit form extensions
 * ************************************************************************************************************
 */

 site.extension('ajaxSubmitForm', {
 	init: function(el, settings) {
 		var element = $(el),
 			errorInputStyle = { 'border-color': '#c00000' };
 			errorClass = 'input-error',
 			processing = false,
 			has = 'hasOwnProperty',
			
			settings = util.extend({
				success: function() {},
				error: function() {},
				mapInputFields: {},
				getSuffixVal: function() { return ''; },
				type: 'post'
			}, settings);

		$('body').on('submit', el, function(e) {

			if(!processing) {

				processing = true;

				var element = $(this),
					action = element.attr('action'),
	            	id =  element.attr('id'),
	            	form = element;

				$.ajax({
					url: action,
	                type: settings.type,
	                dataType: 'json',
	                data: element.serialize({checkboxesAsBools: true}),
	                success: function(data){

	                	// remove previous error inputs style
                		form.find('.' + errorClass)
                		.removeAttr('style')
                		.removeClass(errorClass);

	                	if(data.success == true) {

	                        settings.success.apply(element, arguments);     

	                    } else {

	                    	var suffix = settings.getSuffixVal.call(element);

	                		util.eachRecursive(data.errors, function(key, value){
                				
	                			if(settings.mapInputFields[has](key)) key = settings.mapInputFields[key];
                				
                				$('#' + key + suffix)
                    			.animate(errorInputStyle)
                    			.addClass(errorClass);
	                		});
	                    
	                    	settings.error.apply(element, arguments); 
	                    }
	                	
	                },

	                error: function() {   
	                	settings.error.apply(element, arguments);
	                },

	                complete: function() {
	                	processing = false;
	                }
				})
			}

			e.preventDefault();
			return false;

		});
 	},

 	destroy: function(el) {
 		$('body').off('submit', el);
 	}
});


/**
 * Color picker extensions
 * ************************************************************************************************************
 */

 site.extension('notify', {

 	ready: false,

 	init: function() {
 		$('#notification_container').remove();
	    var template = '<div id="notification_container">' + 
	                        '<div id="basic-template">' +
	                            '<a class="ui-notify-cross ui-notify-close" href="#">x</a>' +
	                            '<h1>#{title}</h1>' +
	                            '<p>#{text}</p>' +
	                        '</div>' +
	                    
	                        '<div id="error-template" class="error_notification">' +
	                            '<a class="ui-notify-cross ui-notify-close" href="#">x</a>' +
	                            '<span class="ui-icon ui-notify-alert"></span>' +
	                            '<h1>#{title}</h1>' +
	                            '<p>#{text}</p>' +
	                        '</div>' +
	                    '</div>';
      
    	$(template).appendTo('body');
    	$('#notification_container').notify({close: function(){$(this).remove()}});
    	this.ready = true;
 	},

 	create: function() {
 		if(!this.ready) this.init();
 		$('#notification_container').notify.apply($('#notification_container'), arguments);
 	}
 });

/**
 * Multiselect extensions
 * ************************************************************************************************************
 */

 site.extension('multiselect', {
 	init: function(el, settings) {

 		var element = $(el);
			
		element.asmSelect(util.extend({
            sortable: false,
            animate: true,
            removeLabel: '',
            selectClass: 'standard_select_form',
            addItemTarget: 'top'
        }, settings));
 	}
 });

/**
 * livequery extensions
 * ************************************************************************************************************
 */

 site.extension('livequery', {
 	init: function(el, fun) {

 		var element = $(el);
	
		element.livequery(function() {
			if(util.is(fun, 'function')) fun.call($(this));
		});
 	}
 });

 /**
 * Datepicker extensions
 * ************************************************************************************************************
 */

 site.extension('datepicker', {
 	init: function(el, settings) {

 		var element = $(el);
			
		element.DatePicker(util.extend({      
            date: element.val(),
            current: element.val(),
            position: 'right',
            eventName: 'focus',

            onChange: function(formated, dates){
 
                if(formated !== 'NaN-NaN-NaN') {
                	element.val(formated);
                }
            }
        }, settings));
 	}
 });

  /**
 * Datepicker extensions
 * ************************************************************************************************************
 */

site.extension('autocomplete', {
 	init: function(el, settings) {

 		var element = $(el);

 		settings = util.extend({      
            unique: true, 
		 	max: 1,
            minLength: 3,
            queryRemote: true,
            placeholder: element.attr('data-suggestion'),
            url: '',
            method: '',
            onlyFromValues: false
        }, settings);

		return new $.TextboxList(el, {
		 	unique: settings.unique, 
		 	max: settings.max, 
		 	plugins: {
		 		autocomplete: {
		 			onlyFromValues: settings.onlyFromValues,
                	minLength: settings.minLength,
                	queryRemote: settings.queryRemote,
                	placeholder: settings.placeholder,
                	remote: {
                		url: settings.url
                	}
                }
            }
        });		
    }
});


